'use strict';

const path = require('path')
const CompressionWebpackPlugin = require('compression-webpack-plugin');

// 是否dev环境
const isDev = process.env.NODE_ENV === 'development';

// path组合-dev
const resolvePath = dir => path.resolve(__dirname, dir);

module.exports = {
    outputDir: 'dist',
    publicPath: '/',
    assetsDir: 'static',
    lintOnSave: isDev, // 关闭eslint，dev开启，生产关闭
    productionSourceMap: false,
    parallel: require('os').cpus().length > 1,
    devServer: {
        host: '0.0.0.0', //本地真机测试
        port: 8080, // 端口号
        open: true, //配置自动启动浏览器
        https: false,
        historyApiFallback: true,
        disableHostCheck: true,
        overlay: {
            warnings: false,
            errors: true
        }
    },
    configureWebpack: {
        //关闭 webpack 的性能提示
        performance: {
            hints: false
        }
    },
    css: {
        extract: true,
        sourceMap: false,
        loaderOptions: {
            sass: {
                additionalData: `
                @import "~@assets/style/mixin.scss";
                @import "~@assets/style/_variables.scss";
                `,
            }
        }
    },
    chainWebpack: config => {
        console.log('NODE_ENV：' + process.env.NODE_ENV);
        // 不是dev环境
        if (!isDev) {
            // 移除 prefetch 插件
            config.plugins.delete('prefetch');
            // 删除预加载
            config.plugins.delete('preload');
            config.plugin('compress').use(CompressionWebpackPlugin, [
                {
                    threshold: 10240, // 超过10kb就压缩
                    test: new RegExp('\\.(' + ['js', 'css', 'svg'].join('|') + ')$'), // 对 js， css, svg 文件都采取 gzip压缩
                    minRatio: 0.8,
                    deleteOriginalAssets: false //压缩后保留原文件
                }
            ]);
            config.optimization
                .minimize(true) // js文件最小化处理
                .splitChunks({ chunks: 'all' }) // 分割代码
                .end();
        }

        // set svg-sprite-loader
        config.module.rule('svg').exclude.add(resolvePath('src/icons')).end();
        config.module
            .rule('svg-sprite-loader')
            .test(/\.(svg)(\?.*)?$/)
            .include.add(resolvePath('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end();

        // 配置解析别名
        config.resolve.alias
            .set('@', resolvePath('src'))
            .set('@components', resolvePath('src/components'))
            .set('@assets', resolvePath('src/assets'))
    },
    configureWebpack: config => {
        // 不是dev环境
        if (!isDev) {
            // 将每个依赖包打包成单独的js文件
            let optimization = {
                runtimeChunk: 'single',
                splitChunks: {
                    chunks: 'all',
                    maxInitialRequests: Infinity,
                    minSize: 20000, // 依赖包超过20000bit将被单独打包
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module) {
                                //node_modules/packageName
                                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
                                // 处理package里面的引用包
                                return `npm.${packageName.replace('@', '')}`;
                            }
                        }
                    }
                }
            };
            Object.assign(config, {
                optimization
            });
        }
    }
}
